﻿package com.ld.hpfs.web.controller;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.jackson.JacksonHelper;
import com.ld.hpfs.common.utils.Const;
import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.common.utils.WriterPrintDataForXML;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.TaskRequest;
import com.ld.hpfs.pojo.TaskResponse;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.CompanyService;
import com.ld.hpfs.service.DealService;
import com.ld.hpfs.service.HistoryService;
import com.ld.hpfs.service.RefTitleService;
import com.ld.hpfs.service.SplitAndMergeService;
import com.ld.hpfs.web.interseptor.WebConstants;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class DealController {
	private static final Logger logger = LoggerFactory
			.getLogger(DealController.class);

	@Autowired
	private DealService dealService;

	@Autowired
	private SplitAndMergeService splitAndMergeService;

	@Autowired
	private RefTitleService refTitleService;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private HistoryService historyService;
	
	@Autowired
	private CompanyService companyService;
	
	String ids=null;

	/*
	 * getDealSearchList 获得查询处理grid信息
	 */

	@RequestMapping(value = "/getDealSearchList", method = RequestMethod.POST)
	public void getDealSearchList(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {

		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		param.put("companyId",
				session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
		/* 高级查询字段 */
		String str = request.getParameter("str") == null ? null
				: (String) request.getParameter("str");

		logger.debug("{}", str + "---------------");

		/* 日期 */
		String DateFirst = request.getParameter("startday") == null ? null
				: (String) request.getParameter("startday");
		String DateEnd = request.getParameter("endday") == null ? null
				: (String) request.getParameter("endday");
		
		String express_date=request.getParameter("express_date") == null ? null
				: (String) request.getParameter("express_date");
		
		String express_date1=request.getParameter("express_date1") == null ? null
				: (String) request.getParameter("express_date1");
		
		String expname=request.getParameter("expname") == null ? null
				: (String) request.getParameter("expname");
		//根据传过来的快递公司名称，模糊查找对应的epress_type
		String expIds="";
		if(expname !=null && expname!=""){
			HashMap<String, Object> ename = new HashMap<String, Object>();
			ename.put("expname", expname);
			List<HashMap<String, Object>> list=dealService.getExpressTypeByname(ename);
			for (int i = 0; i < list.size(); i++) {
				 expIds +="'"+list.get(i).get("EXP_ID").toString()+"'"+",";
			}
			
		}
		if(expIds !="" && expIds !=null){
			int end=expIds.lastIndexOf(",");	
			expIds=expIds.substring(0,end);
		}
		String express_no=request.getParameter("expressno") == null ? null
				: (String) request.getParameter("expressno");
		String express_no1=request.getParameter("expressno1") == null ? null
				: (String) request.getParameter("expressno1");
		/* 发票号码 */
		String Doc_no = request.getParameter("doc_no") == null ? null
				: (String) request.getParameter("doc_no");
		String Doc_no_End = request.getParameter("doc_no_2") == null ? null
				: (String) request.getParameter("doc_no_2");

		/* 单据号grid */
		/* 得到一个或多个单据号 */
		String DOCUMENT_NO = request.getParameter("nums") == null ? null
				: (String) request.getParameter("nums");

		/* 对单据号进行判断不为空的话放入集合之中 */
		if (DOCUMENT_NO != null && DOCUMENT_NO != "") {
			List<HashMap<String, String>> lists = new ArrayList<HashMap<String, String>>();
			String[] ids = DOCUMENT_NO.split(",");
			HashMap<String, String> map = new HashMap<String, String>();
			for (int i = 0; i < ids.length; i++) {
				map = new HashMap<String, String>();
				map.put("id", ids[i]);
				lists.add(map);
			}
			param.put("DOCUMENT_NO", lists);
		} else {
			param.put("DOCUMENT_NO", null);
		}
		
		if(expIds !=null && expIds != ""){
			param.put("expname",expIds);
		}
		if(express_date !=null && express_date != ""){
			param.put("express_date",express_date);
		}
		if(express_date1 !=null && express_date1 != ""){
			param.put("express_date1",express_date1);
		}
		if(express_no !=null && express_no != ""){
			param.put("express_no",express_no);
		}
		if(express_no1 !=null && express_no1 != ""){
			param.put("express_no1",express_no1);
		}

		/* 单据号的开始和结束范围 */
		String DOCUMENT_NO_First = request.getParameter("startnum") == null ? null
				: (String) request.getParameter("startnum");
		String DOCUMENT_NO_End = request.getParameter("endnum") == null ? null
				: (String) request.getParameter("endnum");

		/* 付款单位 */
		String custname = request.getParameter("custname") == null ? null
				: (String) request.getParameter("custname");

		/* 商品名称 */
		String goodsname = request.getParameter("goodsname") == null ? null
				: (String) request.getParameter("goodsname");
		if (goodsname != null && goodsname != "") {
			param.put("goodsname", goodsname);
			ArrayList<HashMap<String, String>> docs = dealService
					.findDocNoByGoodsName(param);// 根据商品名称找到对应的单据号
			if (!docs.isEmpty()) {
				HashMap<String, String> map = new HashMap<String, String>();
				List<HashMap<String, String>> lists = new ArrayList<HashMap<String, String>>();
				for (HashMap<String, String> h : docs) {
					String doc = h.get("DOCUMENT_NO");
					map = new HashMap<String, String>();
					map.put("id", doc);
					lists.add(map);
				}
				param.put("DOCUMENT_NO", lists);
			}
		}
		/* 拆分/合并状态 */
		String state1 = request.getParameter("state1") == null ? null
				: (String) request.getParameter("state1");
		// String state1 ="";
		/* 单据状态 */
		String state2 = request.getParameter("state2") == null ? null
				: (String) request.getParameter("state2");

		/* 发票状态 */
		String state3 = request.getParameter("state3") == null ? null
				: (String) request.getParameter("state3");
		// 将前台所得的各种参数放入param中用于向后台发送数据来获得前台所需的数据
		param.put("str", str);

		param.put("DOCUMENT_NO_First", DOCUMENT_NO_First);
		param.put("DOCUMENT_NO_End", DOCUMENT_NO_End);
		param.put("DateFirst", DateFirst);
		param.put("DateEnd", DateEnd);
		param.put("Doc_no", Doc_no);
		param.put("Doc_no_End", Doc_no_End);

		param.put("custname", custname);

		param.put("state1", state1);
		param.put("state2", state2);
		param.put("state3", state3);
		String language = (String) session
				.getAttribute(WebConstants.CURRENT_LANG);
		param.put("language", language);
		HashMap<String, Object> orderBy = new HashMap<String, Object>();
		orderBy.put("id_head_id", "ID_HEAD_ID");
		try {
			ArrayList<Map<String, String>> field = page.getSortField();
			StringBuffer sort = new StringBuffer("");
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				// 设置显示在前台的数据范围
				param.put("pageStart", page.getStart());
				param.put("pageEnd", page.getStart() + page.getLimit());
				if (field != null && field.size() > 0) {
					for (Map<String, String> map1 : field) {
						sort.append(map1.get("property") + " "
								+ map1.get("direction") + ",");
					}
					param.put("orderBy", sort.substring(0, sort.length() - 1));// 得到排序规则的参数
				} else {
					param.put("orderBy", " ID_HEAD_ID");
				}
				logger.debug("{}", "---------------");
				logger.debug("{}", param);
				ArrayList<HashMap<String, Object>> logs = dealService
						.getDealSearchList(param);// 得到查询条件的结果集
				logger.debug("{}", logs);
				if (logs != null && logs.size() > 0) {// 准备前台所需的各种数据
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", logs);
				} else {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);// 传到前台显示
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}

	}

	/*
	 * getDealSearchList 获得发票打印grid信息
	 */
	@RequestMapping(value = "/getDealPrintList")
	public void getDealPrintList(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {

		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		param.put("companyId",
				session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
		/* 高级查询字段 */
		String str = request.getParameter("str") == null ? null
				: (String) request.getParameter("str");
		String order_param = request.getParameter("order_param") == "" ? null
				: (String) request.getParameter("order_param");
		logger.debug("{}", str + "---------------");

		String doc_type_code = request.getParameter("type") == null ? null
				: (String) request.getParameter("type");
		if (doc_type_code == null || doc_type_code == "") {
			doc_type_code = "BT";
		}
		/* 日期 */
		String DateFirst = request.getParameter("startday") == null ? null
				: (String) request.getParameter("startday");
		String DateEnd = request.getParameter("endday") == null ? null
				: (String) request.getParameter("endday");

		/* 发票号码 */
		String Doc_no = request.getParameter("doc_no") == null ? null
				: (String) request.getParameter("doc_no");
		String Doc_no_End = request.getParameter("doc_no_2") == null ? null
				: (String) request.getParameter("doc_no_2");

		/* 单据号grid */
		/* 得到一个或多个单据号 */
		String DOCUMENT_NO = request.getParameter("nums") == null ? null
				: (String) request.getParameter("nums");

		/* 对单据号进行判断不为空的话放入集合之中 */
		if (DOCUMENT_NO != null && DOCUMENT_NO != "") {
			List<HashMap<String, String>> lists = new ArrayList<HashMap<String, String>>();
			String[] ids = DOCUMENT_NO.split(",");
			HashMap<String, String> map = new HashMap<String, String>();
			for (int i = 0; i < ids.length; i++) {
				map = new HashMap<String, String>();
				map.put("id", ids[i]);
				lists.add(map);
			}
			param.put("DOCUMENT_NO", lists);
		} else {
			param.put("DOCUMENT_NO", null);
		}

		/* 单据号的开始和结束范围 */
		String DOCUMENT_NO_First = request.getParameter("startnum") == null ? null
				: (String) request.getParameter("startnum");
		String DOCUMENT_NO_End = request.getParameter("endnum") == null ? null
				: (String) request.getParameter("endnum");

		/* 付款单位 */
		String custname = request.getParameter("custname") == null ? null
				: (String) request.getParameter("custname");

		/* 商品名称 */
		String goodsname = request.getParameter("goodsname") == null ? null
				: (String) request.getParameter("goodsname");
		if (goodsname != null && goodsname != "") {
			param.put("goodsname", goodsname);
			ArrayList<HashMap<String, String>> docs = dealService
					.findDocNoByGoodsName(param);// 根据商品名称找到对应的单据号
			if (!docs.isEmpty()) {
				HashMap<String, String> map = new HashMap<String, String>();
				List<HashMap<String, String>> lists = new ArrayList<HashMap<String, String>>();
				for (HashMap<String, String> h : docs) {
					String doc = h.get("DOCUMENT_NO");
					map = new HashMap<String, String>();
					map.put("id", doc);
					lists.add(map);
				}
				param.put("DOCUMENT_NO", lists);
			}
		}
		/* 拆分/合并状态 */
		String state1 = request.getParameter("state1") == null ? null
				: (String) request.getParameter("state1");
		// String state1 ="";
		/* 单据状态 */
		String state2 = request.getParameter("state2") == null ? null
				: (String) request.getParameter("state2");

		// 将前台所得的各种参数放入param中用于向后台发送数据来获得前台所需的数据
		param.put("str", str);

		param.put("DOCUMENT_NO_First", DOCUMENT_NO_First);
		param.put("DOCUMENT_NO_End", DOCUMENT_NO_End);
		param.put("DateFirst", DateFirst);
		param.put("DateEnd", DateEnd);
		param.put("Doc_no", Doc_no);
		param.put("Doc_no_End", Doc_no_End);

		param.put("custname", custname);

		param.put("state1", state1);
		param.put("state2", state2);

		param.put("doc_type_code", doc_type_code);

		HashMap<String, Object> orderBy = new HashMap<String, Object>();
		orderBy.put("id_head_id", "ID_HEAD_ID");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				// 设置显示在前台的数据范围
				param.put("pageStart", page.getStart());
				param.put("pageEnd", page.getStart() + page.getLimit());
				if (order_param == null) { // 用于结果集的排序规则
					String initOrder = dealService.getInitOrderStr(param);
					initOrder = initOrder.equals("") ? "ID_HEAD_ID" : initOrder;
					param.put("orderBy", initOrder);
				} else {
					param.put("orderBy", order_param);
				}
				logger.debug("{}", "---------------");
				logger.debug("{}", param);
				String language = (String) session
						.getAttribute(WebConstants.CURRENT_LANG);
				param.put("language", language);
				ArrayList<HashMap<String, Object>> logs = dealService
						.getDealPrintList(param);// 得到查询条件的结果集
				logger.debug("{}", logs);
				if (logs != null && logs.size() > 0) {// 准备前台所需的各种数据
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", logs);
				} else {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);// 传到前台显示
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * getDealFieldList 获得供排序选择的字段列表
	 */
	@RequestMapping(value = "/getDealFieldList")
	public void getDealFieldList(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("lang", session.getAttribute(WebConstants.CURRENT_LANG)
					.toString());
			param.put("companyId",
					session.getAttribute(WebConstants.CURRENT_COMPANY)
							.toString());
			ArrayList<HashMap<String, Object>> result = dealService
					.getDealFieldList(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * savePrintOrder 保存排序到信息表TAX_INV_PRINT_ORDER
	 */
	@RequestMapping(value = "/savePrintOrder")
	public void savePrintOrder(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String[] strs = request.getParameterValues("strs") == null ? null
				: (String[]) request.getParameterValues("strs");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
				HashMap<String, Object> map = new HashMap<String, Object>();
				if (strs != null) {
					for (int i = 0; i < strs.length; i++) {
						map = new HashMap<String, Object>();
						String[] each = strs[i].split(" ");
						String isAsc = each[1].equals("asc") ? "1" : "0";
						map.put("name", each[0]);
						map.put("isAsc", isAsc);
						map.put("pos", i);
						list.add(map);
					}
				}
				param.put("list", list);
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
				int ret = dealService.savePrintOrder(param);
				if (ret == 0) {
					result.put("resultcode", 0);
				} else {
					result.put("resultcode", 9);
				}
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * getPrintOrder 获取排序信息到弹出框中
	 */
	@RequestMapping(value = "/getPrintOrder")
	public void getPrintOrder(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId",
					session.getAttribute(WebConstants.CURRENT_COMPANY)
							.toString());
			ArrayList<HashMap<String, Object>> result = dealService
					.getPrintOrder(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * dealPrintDownload 发票打印->导出航天
	 */
	@RequestMapping(value = "/dealPrintDownload/{type}/download", method = RequestMethod.GET)
	public void dealPrintDownload(@PathVariable String type, HttpSession session, HttpServletResponse response) {
        String Ids = (String) session.getAttribute("ids");
        // 从库中获取信息
        HashMap<String, Object> param = new HashMap<String, Object>();
        param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
        String initOrder = dealService.getInitOrderStr(param);
        if (initOrder.equals("")) {
            initOrder = "ID_HEAD_ID";
        }

        param.put("order", initOrder);// 排序规则
        List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        String[] ids = Ids.split(",");
        for (String id : ids) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("id", id);
            list.add(map);
        }
        param.put("list", list);// 要导出的id_head_id
        param.put("type", type);// 发票类型
        logger.debug("{}", list);

        // 更新update_id,update_name信息 by guxiaoli
        User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
        param.put("update_id", Integer.parseInt(user.getUserId()));
        param.put("update_name", user.getAccount());

        ArrayList<HashMap<String, Object>> revenueData = dealService.getDealPrintForExport(param);
        StringBuffer writer = new StringBuffer();
        String data = FormateDownloadData(revenueData);
        writer.append(data);
        response.setCharacterEncoding("GBK");
        // 创建txt
        HashMap<String, Object> paramCompany = new HashMap<String, Object>();
        paramCompany.put("companyHid",session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
        HashMap<String, Object> hashCompanyCode=companyService.getCurrentCompanyCode(paramCompany);
        String curCompanyCode=hashCompanyCode.get("COMPANY_CODE").toString();

        SimpleDateFormat now = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String fileName=curCompanyCode+"_"+type+"_"+now.format(new Date());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt");

        /* 创建输出流 */
        OutputStream servletOS = null;
		try {
            servletOS = response.getOutputStream();
            IOUtils.write(writer.toString().getBytes("GBK"), servletOS);
			servletOS.flush();
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
            IOUtils.closeQuietly(servletOS);
		}
	}

	private String FormateDownloadData(
			ArrayList<HashMap<String, Object>> revenueData) {// 拼写txt文件内容
		StringBuffer sb = new StringBuffer();
		sb.append("SJJK0101~~销售单据传入~~");
		sb.append("\r\n");
		if (!revenueData.isEmpty()) {
			for (int i = 0; i < revenueData.size(); i++) {
				String outCode = revenueData.get(i).get("outCode").toString();
				if (outCode == "") {
					outCode = revenueData.get(i).get("DOCUMENT_NO").toString();
				}
				String cust_name_chn = revenueData.get(i).get("CUST_NAME_CHN")
						.toString();
				String tax_code = revenueData.get(i).get("TAX_CODE").toString();
				String address = revenueData.get(i).get("ADDRESS").toString();
				String bank_account = revenueData.get(i).get("BANK_ACCOUNT")
						.toString();
				String remark = revenueData.get(i).get("REMARK").toString();
				String checker = revenueData.get(i).get("CHECKER").toString();
				String remittee = revenueData.get(i).get("REMITTEE").toString();
				String goods_list_name = revenueData.get(i)
						.get("GOODS_LIST_NAME").toString();
				String document_date = revenueData.get(i).get("DOCUMENT_DATE")
						.toString();
				String seller_bank_account = revenueData.get(i)
						.get("SELLER_BANK_ACCOUNT").toString();
				String seller_address = revenueData.get(i)
						.get("SELLER_ADDRESS").toString();
				String count = revenueData.get(i).get("count").toString();
				sb.append(outCode).append("~~").append(count).append("~~")
						.append(cust_name_chn).append("~~").append(tax_code)
						.append("~~").append(address).append("~~")
						.append(bank_account).append("~~").append(remark)
						.append("~~").append(checker).append("~~")
						.append(remittee).append("~~").append(goods_list_name)
						.append("~~").append(document_date).append("~~")
						.append(seller_bank_account).append("~~")
						.append(seller_address);
				sb.append("\r\n");
				if (Integer.parseInt(count) > 0) {
					ArrayList<HashMap<String, Object>> details = (ArrayList<HashMap<String, Object>>) revenueData
							.get(i).get("details");
					for (int j = 0; j < details.size(); j++) {
						String goods_name = details.get(j).get("GOODS_NAME")
								.toString();
						String goods_unit = details.get(j).get("GOODS_UNIT")
								.toString();
						String spec = details.get(j).get("SPEC").toString();
						String goods_quantityname_chn = details.get(j)
								.get("QUANTITY").toString();
						String amount_cur = details.get(j).get("AMOUNT_CUR")
								.toString();
						String tax_rate = details.get(j).get("TAX_RATE")
								.toString();
						String tax_item = details.get(j).get("TAX_ITEM")
								.toString();
						String discount_sum = details.get(j)
								.get("DISCOUNT_SUM").toString();
						String tax_amount = details.get(j).get("TAX_AMOUNT")
								.toString();
						String discount_tax = details.get(j)
								.get("DISCOUNT_TAX").toString();
						String discount_rate = details.get(j)
								.get("DISCOUNT_RATE").toString();
						String price_cur = details.get(j).get("PRICE_CUR")
								.toString();
						String price_way = details.get(j).get("PRICE_WAY")
								.toString();
						sb.append(goods_name).append("~~").append(goods_unit)
								.append("~~").append(spec).append("~~")
								.append(goods_quantityname_chn).append("~~")
								.append(amount_cur).append("~~")
								.append(tax_rate).append("~~").append(tax_item)
								.append("~~").append(discount_sum).append("~~")
								.append(tax_amount).append("~~")
								.append(discount_tax).append("~~")
								.append(discount_rate).append("~~")
								.append(price_cur).append("~~")
								.append(price_way);
						sb.append("\r\n");
					}
				}
			}
		}
		try {
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}

	/*
	 * setDeInvoiced状态控制->置为未开
	 */
	@RequestMapping(value = "/setDeInvoiced", method = RequestMethod.POST)
	public void setDeInvoiced(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String idStr = request.getParameter("idStr") == null ? null
				: (String) request.getParameter("idStr");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param = new HashMap<String, Object>();
				List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
				String[] ids = idStr.split(",");
				HashMap<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < ids.length; i++) {
					map = new HashMap<String, String>();
					map.put("id", ids[i]);
					list.add(map);
				}
				param.put("list", list);
				// 更新update_id,update_name信息 by guxiaoli
				param.put("update_id", Integer.parseInt(user.getUserId()));
				param.put("update_name", user.getAccount());
				int ret;
				ret = dealService.setDeInvoiced(param);
				if (ret == 0) {
					result.put("resultcode", 0);
				} else {
					result.put("resultcode", 9);
				}
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * setInvoiced状态控制->置为已开
	 */
	@RequestMapping(value = "/updateStateFlag", method = RequestMethod.POST)
	public void updateStateFlag(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		String stateFlag = request.getParameter("stateFlag") == null ? null
				: (String) request.getParameter("stateFlag");
		String ID_HEAD_ID = request.getParameter("ID_HEAD_ID") == null ? null
				: (String) request.getParameter("ID_HEAD_ID");
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			param.put("stateFlag", stateFlag);
			param.put("ID_HEAD_ID", ID_HEAD_ID);
			// 数据库更新条数
			dealService.updateStateFlag(param);
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * setInvoiced状态控制->置为已开
	 */
	@RequestMapping(value = "/setInvoiced", method = RequestMethod.POST)
	public void setInvoiced(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String id = request.getParameter("id") == null ? null
				: (String) request.getParameter("id");
		String code = request.getParameter("code") == null ? null
				: (String) request.getParameter("code");
		String number = request.getParameter("number") == null ? null
				: (String) request.getParameter("number");
		String date = request.getParameter("date") == null ? null
				: (String) request.getParameter("date");

		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param = new HashMap<String, Object>();
				param.put("id", id);
				param.put("code", code);
				param.put("number", number);
				param.put("date", date);
				int ret;
				// 更新update_id,update_name信息 by guxiaoli
				param.put("update_id", Integer.parseInt(user.getUserId()));
				param.put("update_name", user.getAccount());
				ret = dealService.setInvoiced(param);
				if (ret == 0) {
					result.put("resultcode", 0);
				} else {
					result.put("resultcode", 9);
				}
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * setKeep状态控制->单据保持
	 */
	@RequestMapping(value = "/setKeep", method = RequestMethod.POST)
	public void setKeep(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String idStr = request.getParameter("idStr") == null ? null
				: (String) request.getParameter("idStr");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param = new HashMap<String, Object>();
				List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
				String[] ids = idStr.split(",");
				HashMap<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < ids.length; i++) {
					map = new HashMap<String, String>();
					map.put("id", ids[i]);
					list.add(map);
				}
				param.put("list", list);
				// 更新update_id,update_name信息 by guxiaoli
				param.put("update_id", Integer.parseInt(user.getUserId()));
				param.put("update_name", user.getAccount());
				int ret;
				ret = dealService.setKeep(param);
				if (ret == 0) {
					result.put("resultcode", 0);
				} else {
					result.put("resultcode", 9);
				}
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * setDeKeep状态控制->解除保持
	 */
	@RequestMapping(value = "/setDeKeep", method = RequestMethod.POST)
	public void setDeKeep(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String idStr = request.getParameter("idStr") == null ? null
				: (String) request.getParameter("idStr");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param = new HashMap<String, Object>();
				List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
				String[] ids = idStr.split(",");
				HashMap<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < ids.length; i++) {
					map = new HashMap<String, String>();
					map.put("id", ids[i]);
					list.add(map);
				}
				param.put("list", list);
				// 更新update_id,update_name信息 by guxiaoli
				param.put("update_id", Integer.parseInt(user.getUserId()));
				param.put("update_name", user.getAccount());
				int ret;
				ret = dealService.setDeKeep(param);
				if (ret == 0) {
					result.put("resultcode", 0);
				} else {
					result.put("resultcode", 9);
				}
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 关联预开
	 */
	@RequestMapping(value = "/setAssociatPreopen", method = RequestMethod.POST)
	public void setAssociatPreopen(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		String idStr = request.getParameter("idStr") == null ? null
				: (String) request.getParameter("idStr");
		HashMap<String, Object> result = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				String[] ids = idStr.split(",");
				HashMap<String, Object> map = new HashMap<String, Object>();

				map.put("id_0", ids[0]);
				map.put("id_1", ids[1]);
				map.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
				// 更新update_id,update_name信息 by guxiaoli
				map.put("update_id", Integer.parseInt(user.getUserId()));
				map.put("update_name", user.getAccount());
				int ret;
				ret = dealService.setAssociatPreopen(map);
				if (ret == 0) {
					result.put("resultcode", 0);
				} else {
					result.put("resultcode", 9);
				}
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 撤销关联预开
	 */
	@RequestMapping(value = "/setAssociatPreclose", method = RequestMethod.POST)
	public void setAssociatPreclose(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		String idStr = request.getParameter("idStr") == null ? null
				: (String) request.getParameter("idStr");
		String idStr1 = request.getParameter("idStr1") == null ? null
				: (String) request.getParameter("idStr1");
		HashMap<String, Object> result1 = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				if (idStr != null || idStr1 != null) {

					List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
					HashMap<String, Object> param = new HashMap<String, Object>();
					String[] ids = idStr.split(",");
					HashMap<String, Object> map = new HashMap<String, Object>();
					for (int i = 0; i < ids.length; i++) {
						map = new HashMap<String, Object>();
						map.put("id", ids[i]); // 传过来的是关联id
						list.add(map);
					}
					param.put("companyId",
							session.getAttribute(WebConstants.CURRENT_COMPANY)
									.toString());
					param.put("list", list);
					// 更新update_id,update_name信息 by guxiaoli
					param.put("update_id", Integer.parseInt(user.getUserId()));
					param.put("update_name", user.getAccount());
					int ret;
					ret = dealService.setAssociatPreclose(param);
					if (ret == 0) {
						result.put("resultcode", 0);
					} else {
						result.put("resultcode", 9);
					}

					String[] ids1 = idStr1.split(",");

					HashMap<String, Object> param1 = new HashMap<String, Object>();
					List<HashMap<String, Object>> list1 = new ArrayList<HashMap<String, Object>>();
					HashMap<String, Object> map1 = new HashMap<String, Object>();
					for (int i = 0; i < ids1.length; i++) {
						map1 = new HashMap<String, Object>();
						map1.put("id", ids1[i]);
						list1.add(map1);
					}
					param1.put("list", list1);
					param1.put("companyId",
							session.getAttribute(WebConstants.CURRENT_COMPANY)
									.toString());
					// 更新update_id,update_name信息 by guxiaoli
					param1.put("update_id", Integer.parseInt(user.getUserId()));
					param1.put("update_name", user.getAccount());
					int ret1;
					ret1 = dealService.setAssociatPreclosere(param1);
					if (ret1 == 0) {
						result1.put("resultcode", 0);
					} else {
						result1.put("resultcode", 9);
					}
				}
			}
			writer.print(JackJson.fromObjectToJson(result));

		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * setToPrint状态置为“已审核”
	 */
	@RequestMapping(value = "/setToPrint", method = RequestMethod.POST)
	public void setToPrint(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String idStr = request.getParameter("idStr") == null ? null
				: (String) request.getParameter("idStr");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> spresult = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				int companyId = (Integer) session.getAttribute(WebConstants.CURRENT_COMPANY);
				String userId = user.getUserId();
				int returnvalue = 0;
				String output = "";
				// 调用存储过程
				spresult = setToPrintSp(idStr, userId, companyId);
				
				returnvalue = Integer.parseInt(spresult.get("returnvalue").toString());
				output = spresult.get("output").toString();
				if (returnvalue == 1) {
					result.put("resultcode", returnvalue);
					result.put("resultvalue", output);
				} else {
					result.put("resultcode", 0);
				}
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	private HashMap<String, Object> setToPrintSp(String ids, String userId, int companyId) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		// 调用存储过程接返回值
		Connection conn = null;
		try {
			CallableStatement proc = null;
			conn = jdbcTemplate.getDataSource().getConnection();
			// 调用存储过程
			proc = conn.prepareCall("{ call sp_tax_approval(?,?,?,?,?) }");
			proc.setInt(1, companyId);
			proc.setInt(2, Integer.parseInt(userId));
			proc.setString(3, ids);
			// 注册输出参数
			proc.registerOutParameter(4, Types.VARCHAR);
			proc.registerOutParameter(5, Types.INTEGER);
			proc.execute();
			// 接收存储过程返回值
			String output = proc.getString(4);
			int returnvalue = proc.getInt(5);
			param.put("output", output);
			param.put("returnvalue", returnvalue);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return param;
	}
	
	/* 在发票打印导出excel时先将票据号的状态设置为'已导出' */
	@RequestMapping(value = "/setExportPrintExcel", method = RequestMethod.POST)
	public void setExportPrintExcel(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {

				int id = (Integer) session
						.getAttribute(WebConstants.CURRENT_COMPANY);
				param.put("company_Id", id);
				String Ids = request.getParameter("Ids");
                session.setAttribute("ids", Ids);
				List<HashMap<String, String>> lists = new ArrayList<HashMap<String, String>>();
				String[] ids = Ids.split(",");
				HashMap<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < ids.length; i++) {
					map = new HashMap<String, String>();
					map.put("id", ids[i]);
					lists.add(map);
				}
				param.put("list", lists);// 要导出的id_head_id
				// 更新update_id,update_name信息 by guxiaoli
				param.put("update_id", Integer.parseInt(user.getUserId()));
				param.put("update_name", user.getAccount());
				int ret;
				ret = dealService.setExportType(param);// 把要导出的信息状态设置为"已导出"
				if (ret == 0) {
					result.put("resultcode", 0);
				} else {
					result.put("resultcode", 9);
				}
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 发票打印----->导出excel
	 */
	@RequestMapping(value = "/dealPrintExportExcel/{invType}/download", method = RequestMethod.GET)
	public ModelAndView dealPrintExportExcel(@PathVariable String invType, HttpSession session) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> tableList = new HashMap<String, Object>();
		int id = (Integer) session.getAttribute(WebConstants.CURRENT_COMPANY);
		param.put("companyId", id);
		// String initOrder = dealService.getInitOrderStr(param);
		// if(initOrder.equals("")){
		// initOrder = "ID_HEAD_ID";
		// }
		//获取当前公司的code
		HashMap<String, Object> paramCompany = new HashMap<String, Object>();
		paramCompany.put("companyHid",id);
		HashMap<String, Object> hashCompanyCode=companyService.getCurrentCompanyCode(paramCompany);
		String curCompanyCode=hashCompanyCode.get("COMPANY_CODE").toString();
		
		// param.put("order", initOrder);//排序规则
		List<HashMap<String, String>> lists = new ArrayList<HashMap<String, String>>();
        String idsStr = (String) session.getAttribute("ids");
        String[] ids = idsStr.split(",");
		HashMap<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < ids.length; i++) {
			map = new HashMap<String, String>();
			map.put("id", ids[i]);
			lists.add(map);
		}
		param.put("list", lists);// 要导出的id_head_id
		param.put("type", invType);// 获得票据类型
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		param.put("update_id", Integer.parseInt(user.getUserId()));
		param.put("update_name", user.getAccount());
		String[] name = new String[100];
		try {
			Connection conn = jdbcTemplate.getDataSource().getConnection();
			Statement st = conn.createStatement();

			String sql = "select top 1 * from TAX_V_ID_HEAD_PRINT_EXCEL";
			if (st.execute(sql)) {
				ResultSet rs = st.getResultSet();

				ResultSetMetaData rsmd = rs.getMetaData();
				int nCount = rsmd.getColumnCount();

				int index = 0;
				for (int i = 5; i <= nCount; i++) {
					String columnName = rsmd.getColumnName(i);
					name[index++] = columnName;
				}
			}
		} catch (SQLException e) {
			logger.error("Exception:", e);
			e.printStackTrace();
		}

		List<HashMap<String, Object>> list = dealService.getExportExcelList(param);
		tableList.put("columnName", name);
		tableList.put("list", list);
		tableList.put("curCompanyCode", curCompanyCode);
		tableList.put("invType", invType);
		return new ModelAndView("DealExcelView", "table", tableList);

	}

    /*
    * 查询处理---导出EXCEL
    * added by Hongwei PENG
    */
    @RequestMapping(value = "/dealSearchExportExcel/download", method = RequestMethod.GET)
    public ModelAndView downloadSearchExportExcel(HttpSession session) {
        String selectedIds = (String) session.getAttribute("selectedIds");
        String[] ids = selectedIds.split(",");

        HashMap<String, Object> param = new HashMap<String, Object>();
        Map<String, Object> temp = new HashMap<String, Object>();
        int companyId = (Integer) session.getAttribute(WebConstants.CURRENT_COMPANY);
        param.put("company_Id", companyId);
        List<HashMap<String, String>> headIds = new ArrayList<HashMap<String, String>>();
        for (String id : ids) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("id", id);
            headIds.add(map);
        }
        param.put("list", headIds);// 要导出的id_head_id
        String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
        param.put("language", language);

        List<HashMap<String, Object>> list = dealService.getSearchExportExcelList(param);
        String titles[] = refTitleService.getRef(session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
        temp.put("list", list);// 导出的数据集
        temp.put("titles", titles);// 参考字段名称数组
        temp.put("language", language);
        return new ModelAndView("DealSearchExcelView", "table", temp);
    }

    /*
	 * 查询处理---保存需要导出EXCEL的ID
	 * added by Hongwei PENG
	 */
    @RequestMapping(value = "/dealSearchExportExcel/saveSelectedIds", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> saveSelectedIdsForDownloadingExcel(@RequestParam("ids") String selectedIds, HttpSession session) {
        session.setAttribute("selectedIds", selectedIds);
        Map<String, String> result = new HashMap<String, String>();
        result.put("url", "/dealSearchExportExcel/download");
        return result;
    }

	/*
	 * 查询处理----删除 2013.06.07 modify guxiaoli
	 */
	@RequestMapping(value = "/dealSearchDelete", method = RequestMethod.POST)
	public void dealSearchDelete(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		String idStr = request.getParameter("idStr") == null ? null
				: (String) request.getParameter("idStr");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");

		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				// param.put("ids", idStr);
				String id = session.getAttribute(WebConstants.CURRENT_COMPANY)
						.toString();
				param.put("company_id", id);
				String ids[] = idStr.split(",");
				int ret = -1;
				if (ids.length > 0) {

					// 用于添加履历
					// 若想保留履历，用下面方法添加删除动作
					for (int i = 0; i < ids.length; i++) {
						HashMap<String, Object> hist_param = new HashMap<String, Object>();
						hist_param.put("uid",
								Integer.parseInt(user.getUserId()));
						hist_param.put("uname", user.getAccount());
						ArrayList<Integer> headIds = new ArrayList<Integer>();
						headIds.add(Integer.parseInt(ids[i]));
						hist_param.put("headIds", headIds);
						historyService.addInvoiceHeadHistory(hist_param, 0,
								false);
					}
					// // 若想删除履历，用下面方法删除该票据的所有履历
					// for(int i = 0; i < ids.length; i++){
					// historyService.deleteInvoiceHistory(Integer.parseInt(ids[i]));
					// }

					ArrayList<String> tempArr = new ArrayList<String>();
					for (int i = 0; i < ids.length; ++i) {
						tempArr.add(ids[i]);
						if (tempArr.size() == 5) {
							String idString = FormateDocIdForDel(tempArr);
							param.put("ids", idString);
							ret = dealService.dealSearchDelete(param);
							tempArr.clear();
						}
					}
					if (tempArr.size() > 0) {
						String idString = FormateDocIdForDel(tempArr);
						param.put("ids", idString);
						ret = dealService.dealSearchDelete(param);
						tempArr.clear();
					}
				}
				result.put("resultcode", ret);
			} else {
				result.put("resultcode", 9);
			}

			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 删除票据时，拼写id字符串 2013.06.07 BY guxiaoli
	 */
	private String FormateDocIdForDel(ArrayList<String> tempArr) {
		StringBuffer idString = new StringBuffer();
		for (int j = 0; j < tempArr.size(); j++) {
			if (j > 0) {
				idString.append(",");
			}
			idString.append(tempArr.get(j).toString());
		}
		try {
			return idString.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}

	/*
	 * AI打印按钮
	 */
	@RequestMapping(value = "/dealPrint", method = RequestMethod.POST)
	public void dealPrint(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer)
			throws IOException {
		response.setContentType("text/plain;charset=UTF-8");

		HashMap<String, Object> result = new HashMap<String, Object>();// 用于向前台返回结果
		HashMap<String, Object> param = new HashMap<String, Object>();// 用于向后台传递参数
		List<HashMap<String, Object>> lists = new ArrayList<HashMap<String, Object>>();// 存放所有单据信息和明细信息

		String Ids = request.getParameter("Ids");// 获得前台传递过来的所有单据号
		// StringBuffer URL =
		// request.getRequestURL();//http://localhost:8080/TAX/dealPrint
		logger.debug("{}", "Ids:" + Ids);
		/* 获得客户端请求的IP地址 */
		String ipAddress = request.getParameter("clientIp");//获得前台传递过来的IP地址
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			 ipAddress = request.getHeader("x-forwarded-for");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
		}
		logger.debug("{}", "ipAddress:" + ipAddress);
		param.put("ipAddress", ipAddress);

		/* 对单据号进行判断不为空的话放入集合之中 */
		if (Ids != null && Ids != "") {
			List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
			String[] ids = Ids.split(",");
			HashMap<String, String> map = new HashMap<String, String>();
			for (int i = 0; i < ids.length; i++) {
				map = new HashMap<String, String>();
				map.put("id", ids[i]);
				list.add(map);
			}
			param.put("DOCUMENT_NO", list);
			logger.debug("{}", "list_NO:" + list);
		} else {
			param.put("DOCUMENT_NO", null);
		}

		String printModeString = request.getParameter("printMode");// 获得前台传递过来的打印方式
		String num = request.getParameter("nums") == null ? "5" : request
				.getParameter("nums");// 获得要打印的张数,只有在半自动的模式下才有值
		int number = Integer.parseInt(num);
		int printMode = Integer.parseInt(printModeString);
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);// 得到当前用户
		int id = (Integer) session.getAttribute(WebConstants.CURRENT_COMPANY); // 获得当前公司id
		param.put("company_id", id);

		int temp = 0;
		logger.debug("{}", "number:" + number);
		logger.debug("{}", "printMode:" + printMode);
		try {
			String[] doc = Ids.split(",");
			HashMap<String, Object> map = new HashMap<String, Object>();
			for (int i = 0; i < doc.length; i++) {
				// map = new HashMap<String,Object>();
				map.put("doc_no", doc[i]);// 得到单据号
				map.put("company_id", id);// 得到公司ID
				List<HashMap<String, Object>> headInfos = dealService
						.getPrintHeadInfo(map);// 根据单据号和公司ID获得head表信息
				HashMap<String, Object> headInfo = headInfos.get(0);
				String DOCUMENT_NO = (String) headInfo.get("DOCUMENT_NO");
				logger.debug("{}", "DOCUMENT_NOS:" + DOCUMENT_NO);
				List<HashMap<String, Object>> deatialInfo = dealService
						.getPrintDetailInfo(map);// 根据单据号和公司ID获得deatial表信息
				HashMap<String, Object> info = new HashMap<String, Object>();// 存放具体某个单据信息和明细信息
				info.put("headInfo", headInfo);
				info.put("deatialInfo", deatialInfo);
				lists.add(info);// 把单据信息和明细添加到集合中
			}
			// /E:/我的/apache-tomcat-6.0.36/wtpwebapps/TAX/WEB-INF/classes/
			temp = 1;

			// String path=
			// this.getClass().getResource("/").getPath()+"config/";
			// File prePrintDataFile = new File(path);
			// if(!prePrintDataFile.exists()){
			// prePrintDataFile.mkdirs();
			// path += "PRINT.xml";
			// prePrintDataFile = new File(path);
			// prePrintDataFile.createNewFile();
			// }else{
			// path += "PRINT.xml";
			// prePrintDataFile = new File(path);
			// prePrintDataFile.createNewFile();
			// }

			// File prePrintDataFile = new File(path+"config/"+"PRINT.xml");
			File prePrintDataFile = new File("PRINT.xml");

			WriterPrintDataForXML.writerDataForXML(lists, user,
					prePrintDataFile);// 用户向file文件中写入数据
			FileInputStream inputStream = new FileInputStream(prePrintDataFile);
			byte[] prePrintDateByte = new byte[inputStream.available()];
			inputStream.read(prePrintDateByte);
			logger.debug("{}", "prePrintDateByte:" + prePrintDateByte);
			// 开始调用ai打印接口
			try {
				boolean success = StartPrinterController.startPrinter(
						ipAddress, prePrintDateByte, printMode, number,
						"invCodeStart", "invNoStart");
				if (success) {// 如果送去打印成功则设置状态'打印中'
					try {
						int QUANTITY = doc.length;
						List<HashMap<String, Object>> ips = dealService
								.getIpAddress(ipAddress);
						if (ips.isEmpty()) {// ip不存在的话保存这条记录
							param.put("QUANTITY", QUANTITY);
							dealService.saveIpAddress(param);// 保存ai打印接口的ip地址,和打印数量
						} else {// ip存在的话更新打印数量
							HashMap<String, Object> ipaddr = ips.get(0);
							String clientIp = (String) ipaddr
									.get("RETOME_ADDR_IP");
							Integer ID = (Integer) ipaddr.get("ID");
							Integer nums = (Integer) ipaddr.get("QUANTITY");// 获得要打印的数量
							param.put("ID", ID);
							param.put("number", QUANTITY + nums);
							param.put("clientIp", clientIp);
							dealService.editNum(param);// 修改数据库中还要打印的条数
						}
						// 更新update_id,update_name信息 by guxiaoli
						param.put("update_id",
								Integer.parseInt(user.getUserId()));
						param.put("update_name", user.getAccount());
						dealService.updateDoc_Status(param);// 将选中的多条打印记录状态为"打印中"

						result.put("resultcode", 0);// 把送去打印成功的信息反馈给前台
						writer.print(JackJson.fromObjectToJson(result));
					} catch (Exception e) {
						result.put("resultcode", 1);// 数据库操作异常
						writer.print(JackJson.fromObjectToJson(result));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				String clientIpPort = Const.PROPERTIES
						.getProperty("clientIpPort");
				result.put("resultcode", 9);// 把送去打印失败的信息反馈给前台
											// 提示：没有打印的设备请到有打印设备的平台上再试
				result.put("resultPort", clientIpPort);
				writer.print(JackJson.fromObjectToJson(result));
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (temp == 0) {
				result.put("resultcode", 1);// 数据库操作异常
				writer.print(JackJson.fromObjectToJson(result));
			} else {
				result.put("resultcode", 2);
				writer.print(JackJson.fromObjectToJson(result));
			}
		}
		// dealService.savePrintList(docs);//把要打印的数据先存储到TAX_C_AI_NUMS表中
	}
	
	/*
	 * 获取查询处理，一般查询单据列表信息
	 */
	@RequestMapping(value = "/getDocumentNO")
	public void getDocumentNO(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			param.put("statusStr", " AND DOC_STATUS NOT IN(6,7) ");
			ArrayList<HashMap<String, Object>> result = dealService
					.getDocumentNO(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 获取查询处理，一般查询单据列表信息
	 */
	@RequestMapping(value = "/getDealSearchNo")
	public void getDealSearchNo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			param.put("statusStr", " AND DOC_STATUS NOT IN(6,7) ");
			ArrayList<HashMap<String, Object>> result = dealService
					.getDocumentNO(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	/*
	 * 获取发票打印和快递单扫描，一般查询单据列表信息
	 */
	@RequestMapping(value = "/getDealPrintNo")
	public void getDealPrintNo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			param.put("statusStr", " AND DOC_STATUS in (1, 10) ");
			ArrayList<HashMap<String, Object>> result = dealService
					.getDocumentNO(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 获取发票号码列表信息getInvoiceNum
	 */
	@RequestMapping(value = "/getInvoiceNum")
	public void getInvoiceNum(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			param.put("statusStr", " AND DOC_STATUS NOT IN (6, 7)");
			ArrayList<HashMap<String, Object>> result = dealService
					.getInvoiceNum(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/*
	 * 发票打印获取发票号码
	 */
	@RequestMapping(value = "/getDealPrintInvoiceNum")
	public void getDealPrintInvoiceNum(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			param.put("statusStr", " AND DOC_STATUS = 1");
			ArrayList<HashMap<String, Object>> result = dealService
					.getInvoiceNum(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/*
	 * 发票打印一般查询:获取发票号码列表信息
	 */
	@RequestMapping(value = "/getDealScanExpressNo")
	public void getDealScanExpressNo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			ArrayList<HashMap<String, Object>> result = dealService
					.getDealScanExpressNo(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/*
	 * 查询处理一般查询:获取付款单位列表信息getCustomList
	 */
	@RequestMapping(value = "/getCustomList")
	public void getCustomList(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			param.put("statusStr", " AND DOC_STATUS not in(6, 7) ");
			ArrayList<HashMap<String, Object>> result = dealService
					.getCustomList(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/*
	 * 查询处理一般查询:获取付款单位列表信息getCustomList
	 */
	@RequestMapping(value = "/getScanCustomList")
	public void getScanCustomList(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			param.put("statusStr", " AND DOC_STATUS = 1,10 ");
			ArrayList<HashMap<String, Object>> result = dealService
					.getCustomList(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 获取商品名称列表信息getGoodsNameList
	 */
	@RequestMapping(value = "/getGoodsNameList")
	public void getGoodsNameList(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			param.put("statusStr", " AND DOC_STATUS NOT IN(6, 7) ");
			ArrayList<HashMap<String, Object>> result = dealService
					.getGoodsNameList(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/*
	 * 发票打印一般查询:获取商品名称列表信息
	 */
	@RequestMapping(value = "/getDealPrintGood")
	public void getDealPrintGood(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			param.put("statusStr", " AND DOC_STATUS = 1 ");
			ArrayList<HashMap<String, Object>> result = dealService
					.getGoodsNameList(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/*
	 * 发票打印一般查询:客户列表信息
	 */
	@RequestMapping(value = "/getDealPrintCust")
	public void getDealPrintCust(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", companyId);
			param.put("statusStr", " AND DOC_STATUS = 1 ");
			ArrayList<HashMap<String, Object>> result = dealService
					.getCustomList(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 手动拆分时获取对应票据明细getDetailListForSplit
	 */
	@RequestMapping(value = "/getDetailListForSplit")
	public void getDetailListForSplit(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		// 参数：document_no
		String doc_no = request.getParameter("doc_no") == "" ? null
				: (String) request.getParameter("doc_no");
		try {
			HashMap<String, Object> param = new HashMap<String, Object>();
			ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
			if (!Tools.isEmpty(doc_no)) {
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY));
				param.put("doc_no", doc_no);
			}
			String language = (String) session
					.getAttribute(WebConstants.CURRENT_LANG);
			param.put("language", language);
			result = dealService.getDetailListForSplit(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 撤销拆分和撤销合并的功能
	 */
	@RequestMapping(value = "/dealStateUnsplitUnmerge", method = RequestMethod.POST)
	public void dealStateUnsplitUnmerge(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> result = new HashMap<String, Object>();// 用于返回前台的显示数据
		HashMap<String, Object> param = new HashMap<String, Object>();// 用于向后台传递参数获得结果集
		String doc_nos = request.getParameter("doc_no") == "" ? null
				: (String) request.getParameter("doc_no");
		String comId = session.getAttribute(WebConstants.CURRENT_COMPANY)
				.toString();
		String[] doc_no = doc_nos.split(",");
		// 获得语言环境
		String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);

		param.put("com_Id", comId);
		int ret = -1;
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				for (int i = 0; i < doc_no.length; i++) {
					String doc = doc_no[i];
					param.put("doc_no", doc);
					ret = splitAndMergeService.revokeSplitMerge(param);
					if (ret != 0) {
						result.put("resultcode", ret);
						break;
					} else if (ret == 0) {
						HashMap<String, Object> params = new HashMap<String, Object>();
						params.put("cpnId", comId);
						params.put("document_no", doc_no[i]);
						params.put("language", language);
						historyService.deleteInvoiceHistoryByDocNo(params);
						result.put("resultcode", ret);
					}
				}
			}

			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);

		} catch (Exception e) {
			logger.error("Exception:", e);
			result.put("resultcode", ret);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 在进行撤销拆分之前先进行票据状态的验证，如果拆分的一批数据中有一条数据的状态不是'未开票'则提示用户不能进行'撤销拆分' 时间：2013/5/15
	 * 10:57 AM 修改人：喻付伟
	 */
	@RequestMapping(value = "/testdealState", method = RequestMethod.POST)
	public void testdealState(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		// 参数：document_no
		String doc_nos = request.getParameter("doc_no") == "" ? null
				: (String) request.getParameter("doc_no");
		HashMap<String, Object> result = new HashMap<String, Object>();
		String[] doc_no = doc_nos.split(",");
		String doc_nofind = "";
		try {
			HashMap<String, Object> param = new HashMap<String, Object>();
			List<HashMap<String, Object>> beforeDoc = new ArrayList<HashMap<String, Object>>();
			param.put("companyId",
					session.getAttribute(WebConstants.CURRENT_COMPANY));

			ArrayList<HashMap<String, Object>> list_yes = new ArrayList<HashMap<String, Object>>();// 满足拆分条件的单据
			ArrayList<HashMap<String, Object>> list_no = new ArrayList<HashMap<String, Object>>();// 不满足拆分条件的单据
			ArrayList<HashMap<String, Object>> list_no_sm = new ArrayList<HashMap<String, Object>>();// 不满足拆分条件并且含有撤销和拆分的单据
			for (int i = 0; i < doc_no.length; i++) {
				doc_nofind = doc_no[i];
				param.put("doc_no", doc_no[i]);
				beforeDoc = dealService.getBeforeDoc(param);// 根据拆分的单据号得到之前未拆分时的单据号
				if (beforeDoc == null || beforeDoc.isEmpty()) {// 如果没有找到
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("DOCUMENT_NO", doc_nofind);
					list_no.add(map);
					continue;
				}
				param.put("beforeDoc", beforeDoc);
				ArrayList<HashMap<String, Object>> BrotherDoc = dealService
						.getBrotherDoc(param);// 根据原始单据号获得拆分时的其他所有拆分数据
				if (BrotherDoc == null || BrotherDoc.isEmpty()) {// 如果没有找到
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("DOCUMENT_NO", doc_nofind);
					list_no.add(map);
					continue;
				}

				param.put("BrotherDoc", BrotherDoc);
				ArrayList<HashMap<String, Object>> docStatus = dealService
						.getdocStatusByBroDoc(param);// 得到所有票据状态
				if (docStatus == null || docStatus.isEmpty()) {// 如果没有找到
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("DOCUMENT_NO", doc_nofind);
					list_no.add(map);
					continue;
				}
				int flag = 0;// 标志位
				Integer doc_status = 0;
				Integer DOC_LOCKED = 0;
				int temp = 0;

				for (HashMap<String, Object> status : docStatus) {// 判断单据中是否有合并或者拆分的数据

					doc_status = (Integer) status.get("DOC_STATUS");
					// String DOCUMENT_NO = (String)status.get("DOCUMENT_NO");
					DOC_LOCKED = (Integer) status.get("DOC_LOCKED");// 0:未保持;
																	// 1:已保持;
					if (doc_status == 6 || doc_status == 7) {
						flag = 1;
						temp = 1;
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("DOC_STATUS", doc_status);
						map.put("DOCUMENT_NO", doc_nofind);
						map.put("DOC_LOCKED", DOC_LOCKED);
						list_no.add(map);
						list_no_sm.add(map);
						break;
					}
				}
				if (temp == 0) {
					for (HashMap<String, Object> status : docStatus) {

						doc_status = (Integer) status.get("DOC_STATUS");
						// 0:未保持, 1:已保持;
						DOC_LOCKED = (Integer) status.get("DOC_LOCKED");
						// 满足撤销的单据信息
						if (doc_status != 0 || DOC_LOCKED != 0) {
							flag = 1;
							HashMap<String, Object> map = new HashMap<String, Object>();
							map.put("DOC_STATUS", doc_status);
							map.put("DOCUMENT_NO", doc_nofind);
							map.put("DOC_LOCKED", DOC_LOCKED);
							list_no.add(map);
							break;
						}
					}
				}

				if (flag == 0) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("DOC_STATUS", doc_status);
					map.put("DOCUMENT_NO", doc_nofind);
					map.put("DOC_LOCKED", DOC_LOCKED);
					list_yes.add(map);
				}
			}
			result.put("list_yes", list_yes);
			result.put("list_no", list_no);
			result.put("list_find", 0);
			result.put("list_no_sm", list_no_sm);

			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put("list_find", 1);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * cancelAudit 发票打印-》取消审核
	 */
	@RequestMapping(value = "/cancelAudit")
	public void cancelAudit(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String idStr = request.getParameter("ids") == null ? null
				: (String) request.getParameter("ids");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param = new HashMap<String, Object>();
				List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
				String[] ids = idStr.split(",");
				HashMap<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < ids.length; i++) {
					map = new HashMap<String, String>();
					map.put("id", ids[i]);
					list.add(map);
				}
				param.put("list", list);
				// 更新update_id,update_name信息 by guxiaoli
				param.put("update_id", Integer.parseInt(user.getUserId()));
				param.put("update_name", user.getAccount());
				int ret;
				ret = dealService.cancelAudit(param);
				if (ret == 0) {
					result.put("resultcode", 0);
				} else {
					result.put("resultcode", 9);
				}
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * getDealScanList 获得快递单扫描grid信息 2013.06.19 BY guxiaoli
	 */
	@RequestMapping(value = "/getDealScanList", method = RequestMethod.POST)
	public void getDealScanList(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			ArrayList<Map<String, String>> field = page.getSortField();
			StringBuffer sort = new StringBuffer("");
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param.put("pageEnd", page.getStart() + page.getLimit());
				if (field != null && field.size() > 0) {
					for (Map<String, String> map : field) {
						sort.append(map.get("property") + " "
								+ map.get("direction") + ",");
					}
					param.put("orderBy", sort.substring(0, sort.length() - 1));
				} else {
					param.put("orderBy", " id_head_id");
				}
				param.put("pageStart", page.getStart());
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY));

				/* 日期 */
				String DateFirst = request.getParameter("startday") == "" ? null
						: (String) request.getParameter("startday");
				String DateEnd = request.getParameter("endday") == "" ? null
						: (String) request.getParameter("endday");
				/* 得到一个或多个单据号 */
				String DOCUMENT_NO = request.getParameter("nos") == "" ? null
						: (String) request.getParameter("nos");
				/* 对单据号进行判断不为空的话放入集合之中 */
				if (DOCUMENT_NO != null && DOCUMENT_NO != "") {
					List<HashMap<String, String>> lists = new ArrayList<HashMap<String, String>>();
					String[] nos = DOCUMENT_NO.split(",");
					HashMap<String, String> map = new HashMap<String, String>();
					for (int i = 0; i < nos.length; i++) {
						map = new HashMap<String, String>();
						map.put("nos", nos[i]);
						lists.add(map);
					}
					param.put("DOCUMENT_NO", lists);
				} else {
					param.put("DOCUMENT_NO", null);
				}
				/* 单据号的开始和结束范围 */
				String DOCUMENT_NO_First = request
						.getParameter("startno") == "" ? null
						: (String) request.getParameter("startno");
				String DOCUMENT_NO_End = request.getParameter("endno") == "" ? null
						: (String) request.getParameter("endno");
				/* 付款单位 */
				String custname = request.getParameter("custom") == "" ? null
						: (String) request.getParameter("custom");
				/* 快递类型 */
				String type = request.getParameter("type") == "" ? null
						: (String) request.getParameter("type");
				/* 快递单号 */
				String sexpressno = request.getParameter("sexpressno") == "" ? null
						: (String) request.getParameter("sexpressno");
				String eexpressno = request.getParameter("eexpressno") == "" ? null
						: (String) request.getParameter("eexpressno");
				param.put("DOCUMENT_NO_First", DOCUMENT_NO_First);
				param.put("DOCUMENT_NO_End", DOCUMENT_NO_End);
				param.put("DateFirst",
						DateFirst == null ? null : DateFirst.substring(0, 10));
				param.put("DateEnd",
						DateEnd == null ? null : DateEnd.substring(0, 10));
				param.put("custname", custname);
				param.put("type", type);
				param.put("sexpressno", sexpressno);
				param.put("eexpressno", eexpressno);
				ArrayList<HashMap<String, Object>> logs = dealService
						.getDealScanList(param);
				if (logs != null && logs.size() > 0) {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", logs);
				} else {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 获取快递公司列表getExpressType 2013.06.19 BY guxiaoli
	 */
	@RequestMapping(value = "/getExpressType")
	public void getExpressType(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
		try {
			result = dealService.getExpressType(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 获取快递公司列表getExpressType1(含全部) 2013.07.11 BY guxiaoli
	 */
	@RequestMapping(value = "/getExpressType1")
	public void getExpressType1(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
		try {
			result = dealService.getExpressType1(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * saveExpressNo保存快递单号
	 */
	@RequestMapping(value = "/saveExpressNo", method = RequestMethod.POST)
	public void saveExpressNo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String id = request.getParameter("id") == null ? null
				: (String) request.getParameter("id");
		String type = request.getParameter("type") == null ? null
				: (String) request.getParameter("type");
		String no = request.getParameter("no") == null ? null
				: (String) request.getParameter("no");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		
		String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param.put("id", id);
				param.put("type", type);
				param.put("no", no);
				param.put("companyId", companyId);
				// 更新update_id,update_name信息 by guxiaoli
				param.put("update_id", Integer.parseInt(user.getUserId()));
				param.put("update_name", user.getAccount());
				int ret = dealService.saveExpressNo(param);
				result.put("resultcode", ret);
				// 检查当前公司是否启用快递100功能
				int expressStatus = dealService.getExpressStatus(companyId);
				if (expressStatus == 1) {
					// 快递单扫描页面当单据有了快递单号时发送快递状态请求
					try {
						HashMap<String, Object> document = new HashMap<String, Object>();
						document = dealService.getDataForExpress(param);
						// 快递公司调用方法
						doExpressImpl(document);
					} catch (Exception e) {
						System.out.println(e);
					}
				}
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 获取快递单号信息getDocumentNO
	 */
	@RequestMapping(value = "/getExpressNO")
	public void getExpressNO(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId",
					session.getAttribute(WebConstants.CURRENT_COMPANY)
							.toString());
			ArrayList<HashMap<String, Object>> result = dealService
					.getExpressNO(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	// 执行AI打印之前先获得一次打印结果
	// @RequestMapping(value = "/getAIPrintInfo")
	// public void getAIPrintInfo(HttpSession session,HttpServletRequest
	// request,HttpServletResponse response,PrintWriter writer){
	// response.setContentType("text/plain;charset=UTF-8");
	// HashMap<String,Object> result = new HashMap<String,Object>();
	// try{
	// User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
	// if(user!=null){
	// String ipAddress = null;
	// ipAddress = request.getHeader("x-forwarded-for");
	// if(ipAddress == null || ipAddress.length() == 0 ||
	// "unknown".equalsIgnoreCase(ipAddress)) {
	// ipAddress = request.getHeader("Proxy-Client-IP");
	// }
	// if(ipAddress == null || ipAddress.length() == 0 ||
	// "unknown".equalsIgnoreCase(ipAddress)) {
	// ipAddress = request.getHeader("WL-Proxy-Client-IP");
	// }
	// if(ipAddress == null || ipAddress.length() == 0 ||
	// "unknown".equalsIgnoreCase(ipAddress)) {
	// ipAddress = request.getRemoteAddr();
	// }
	// logger.debug("{}", "ipAddress---:"+ipAddress);//获得客户端IP地址
	//
	//
	// ArrayList<HashMap<String,Object>> stubs =
	// GetPrintedStub.getPrintedStub(ipAddress);//获得打印结果集
	// if(stubs ==null || stubs.isEmpty()){
	// result.put("resultcode",0);
	// }else{
	// dealService.updateDoc_StatusTo1(stubs);//把打印成功的结果集的状态改为"已开票"
	// result.put("resultcode",0);
	// }
	// }
	// writer.print(JackJson.fromObjectToJson(result));
	// }catch (Exception e){
	// logger.error("Exception:",e);
	// }finally {
	// writer.flush();
	// writer.close();
	// }
	// }

	/**
	 * 获取快递单跟踪信息
	 */
	@RequestMapping(value = "/getExpressInfo")
	public void getExpressInfo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		// 获取当前公司快递100是否启用
		int expressStatus = dealService.getExpressStatus(companyId);
		if (expressStatus == 1) {
			// 获取请求参数
			String express = request.getParameter("express");
			String express_no = request.getParameter("express_no");
			
			// 查询快递公司代码参数
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("express", express);
			// 查询快递公司代码
			String expressCompanyCode = dealService.getExpressCode(param);
			// 查询服务器上的快递跟踪信息
			HashMap<String, String> p = new HashMap<String, String>();
			p.put("expressCompanyCode", expressCompanyCode);
			p.put("expressNo", express_no);

			try {
				String result = HttpRequest.postData(Const.PROPERTIES.getProperty("express.websit.get"), p, "UTF-8");
				writer.print(result);
			} catch (MalformedURLException e) {
				e.printStackTrace();
				writer.print(Const.PROPERTIES.getProperty("express.warning"));
			} catch (IOException e) {
				e.printStackTrace();
				writer.print(Const.PROPERTIES.getProperty("express.warning"));
			} catch (Exception e) {
				logger.error("Exception: ", e);
				writer.print(Const.PROPERTIES.getProperty("express.warning"));
			} finally {
				writer.flush();
				writer.close();
			}
		}
	}

	/**
	 * 验证发票图片是否存在
	 */
	@RequestMapping(value = "/getDocPath")
	public void getDocPath(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try{
			HashMap<String, Object> result = new HashMap<String, Object>();
			// 接收到的文件名 
			String fileName = request.getParameter("picName");
			// 拼出图片在服务器上的路径
			String basepath = Const.REAL_PATH;
			basepath = basepath.substring(0, basepath.indexOf("webapps")) + "webapps\\invoicePic\\";
			String picUrl = basepath + fileName + ".jpg";
			System.out.println(picUrl);
			File fi = new File(picUrl);
			//如果文件存在 ，则 返回1和图片路径
			if(fi.isFile()){
				result.put("exists", 1);
				result.put("picUrl", Const.PROPERTIES.getProperty("basepath") + "invoicePic/" + fileName + ".jpg");
			} else {
				//如果文件不存在， 返回 0 
				result.put("exists", 0);
			}
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		}catch (Exception e){
			logger.error("Exception:",e);
		}finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 获取发票代码和号码
	 */
	@RequestMapping(value = "/getInvoiceNCode")
	public void getInvoiceNCode(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){ 
		response.setContentType("text/plain;charset=UTF-8");
		try{
			// 获取单据号
			String picName = "";
			String docNo = request.getParameter("num");
			HashMap<String,Object> param = new HashMap<String,Object>();
			param.put("docNo", docNo);
			HashMap<String,Object> result = dealService.getInvoiceNCode(param);
		    // 发票号码
			String invNumber = (String) result.get("INVOICE_NO");
			// 发票代码
			String invCode = (String) result.get("INVOICE_CODE");
			// 发票图片名
			picName = invNumber + invCode;
			writer.print(picName);
			}catch (Exception e){
				logger.error("Exception:",e);
			}finally {
				writer.flush();
				writer.close();
        	}
	}
	/**
	 * 调用快递100公司接口并发送推送请求
	 */
	public void doExpressImpl(HashMap<String, Object> document) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		try {
			// 回执url
			String callbackurl = Const.PROPERTIES.getProperty("callbackurl");
			// 推送秘钥
			String key = Const.PROPERTIES.getProperty("key");
			// 快递公司
			String exp_company = document.get("express_cpn").toString();
			// 快递单号
			String exp_no = document.get("express_no").toString();
			TaskRequest req = new TaskRequest();
			req.setCompany(exp_company);
			req.setNumber(exp_no);
			req.getParameters().put("callbackurl", callbackurl);
			req.setKey(key);
			HashMap<String, String> p = new HashMap<String, String>();
			p.put("schema", "json");
			p.put("param", JacksonHelper.toJSON(req));
			String returnData = HttpRequest.postData(
					Const.PROPERTIES.getProperty("expressserver"), p, "UTF-8");
			TaskResponse resp = JacksonHelper.fromJSON(returnData,
					TaskResponse.class);
			if (resp.getReturnCode() == 200) {
				result.put("expressCode", 0);
				System.out.println(returnData);
			} else {
				result.put("expressCode", 1);
				System.out.println(returnData);
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}
	
	
	/*
	 * 获取查询处理，一般查询快递公司信息
	 */
	@RequestMapping(value = "/getExpressType2")
	public void getExpressType2(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		try {
			ArrayList<HashMap<String, Object>> result = dealService
					.getExpressType2();
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	
	
	
	
	}
	
}